package IOTWeb.com.handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import IOTWeb.com.dao.CarOrPersionCheck;
import IOTWeb.com.dao.ExcepContent;
import IOTWeb.com.dao.meth.CheckMeth;
import IOTWeb.com.dao.meth.ExcepContentMeth;
import IOTWeb.com.utils.FileOption;
import IOTWeb.com.utils.H2ConnectionPool;
import IOTWeb.com.utils.HttpRequestFormOtherResolver;
import IOTWeb.com.utils.Utils;

public class ScanContentHandler implements HttpHandler {

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		new Thread(new Runnable() {
			@Override
            public void run() {
				try {	
		            System.out.println("url: " + exchange.getRequestURI().toString());
		            CarOrPersionCheck car = new CarOrPersionCheck();
		            CheckMeth carCheckMeth = new CheckMeth();
					Utils utils = new Utils();
		    		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		    		java.sql.Date sDate = null;
					String queryString = exchange.getRequestURI().getQuery();//get:获得url后面的值
					Map<String, String> queryStringInfo = utils.formData2Dic(queryString);
		    		String result = "";
					Headers headers = exchange.getRequestHeaders();
					List<String> tocken = headers.get("token");
					FileOption fileOption = new FileOption();
					Map<String, String> filemap = fileOption.fileMap();
					Headers responseHeaders = exchange.getResponseHeaders();
					utils.setResponseJs(responseHeaders, filemap.get("txt"));
					OutputStream os = exchange.getResponseBody();
					PrintStream out = new PrintStream(os);
					if(tocken != null && !tocken.isEmpty() && utils.haveTocken(tocken)) {
						Integer id = Integer.valueOf(queryStringInfo.get("id"));
						result = carCheckMeth.selectOneCheck(id);
						byte[] bytes = result.getBytes("utf-8");
						int len = bytes.length;
						exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, len);
						out.write(bytes, 0, bytes.length);
						out.flush();
						out.close();
					}else {
						utils.tockenError(exchange);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

}
